import tools from "../tools"

export default class ListList extends Element {
    componentDidMount() {
        this.fetchData()
    }

    /**
     * 列表数据
     * @type {[]}
     */
    list = []
    fetchData() {
        tools.async_xcall("async_get_list_val", window.redis_key, Number(this.page.current), Number(this.page.size))
            .then(res => {
                if (res.code !== 200) {
                    return
                }
                const {current,size,list,total} = res.data
                this.page.current =current
                this.page.size = size
                this.page.total = total
                this.list = list
                this.componentUpdate()
            })
    }
    /**
     * 导出数据
     */
    exportFile(data) {
        let f = tools.getView().selectFile({
            mode: "save",
            filter: "JSON文件|*.json",
            caption: `保存为`,
            path: `${window.redis_key}.json`
        })
        if (f) {
            tools.sys.fs.open(f.slice(7), "wb+")
                .then(fd => {
                    return fd.write(data)
                })
                .then(() => {
                    tools.alert("保存成功！")
                })
                .catch(e => {
                    tools.alert("保存失败：" + e.message)
                })
        }
    }
    /**
     * 分页
     * @type {{current: number, total: number, size: number}}
     */
    page = {
        current: 1,
        size: 10,
        total: 0
    }
    setPage = ""
    timer = -1
    /**
     * 渲染分页
     * @param cb
     * @returns {JSX.Element}
     */
    renderPage(cb) {
        let max = 10
        let count = Math.ceil(this.page.total / this.page.size)
        let start = 1
        let end = 10
        let rects = []
        // 最多渲染个数
        if (count <= max) {
            end = count
        } else {
            // 当总渲染个数减去当前页小于渲染个数时最大渲染数为count，开始值为count-max
            if (this.page.current + Math.ceil(max / 2) >= count) {
                start = count - max
                end = count
            } else {
                start = this.page.current > Math.floor(max / 2) ? this.page.current - Math.floor(max / 2) : 1
                end = start - 1 + max
            }
        }
        for (let i = start; i <= end; i++) {
            if (i === Number(this.page.current)) {
                rects.push(<div class="disable navigation-item">{i}</div>)
            } else {
                rects.push(<div class="navigation-item" onClick={() => cb(i)}>{i}</div>)
            }
        }
        return <div class="navigation">
            <div class="total">共{this.page.total}条</div>
            <div class="jump-to">
                <select value={"" + this.page.size} onChange={(evt, ele) => {
                    this.page.size = Number(ele.value)
                    clearTimeout(this.timer)
                    this.timer = setTimeout(() => {
                        this.fetchData()
                    }, 10)
                }}>
                    <option value="10">10条/页</option>
                    <option value="20">20条/页</option>
                    <option value="50">50条/页</option>
                    <option value="100">100条/页</option>
                </select>
            </div>
            {
                this.page.current > 1 && <div class="navigation-item" onClick={(evt) => {
                    evt.stopPropagation()
                    this.page.current = this.page.current - 1
                    this.fetchData()
                }}><i class="icon icon-arrow-left"></i></div>
            }
            {rects}
            {
                this.page.current < count && <div class="navigation-item" onClick={(evt) => {
                    evt.stopPropagation()
                    this.page.current = Number(this.page.current) + 1
                    this.fetchData()
                }}><i class="icon icon-arrow-right"></i></div>
            }
            <div class="jump-to">前往<input onKeyUp={evt=> {
                const keyCode = evt.keyCode
                if (keyCode == 36 || keyCode == 76) {
                    this.fetchData()
                }
            }} type="text" value={this.setPage}
                                          onChange={(evt, ele) => {
                                              if (!/^\d+$/g.test(ele.value)) {
                                                  return this.setPage = ""
                                              }
                                              if (ele.value > count) {
                                                  return this.setPage = ""
                                              }
                                              if (ele.value < 1) {
                                                  return this.setPage = ""
                                              }
                                              if (ele.value >= 1 && ele.value <= count) {
                                                  this.setPage = ele.value
                                              }
                                              this.page.current = this.setPage
                                          }}/>页
            </div>
        </div>
    }

    render() {
        return <div class="list-info">
            <div class="list-info-title">
                <span><b>{window.redis_key}</b>查询结果</span>
                <div class="list-info-title-action">
                    <div class="btn" onClick={() => {
                        setTimeout(() => {
                            let [x, y] = tools.windowPosition()
                            let [w, h] = tools.windowSize()
                            let scale = devicePixelRatio
                            let width = 320 * scale
                            let height = 240 * scale
                            let modal = tools.getView().modal({
                                width,
                                height,
                                x: x + w / 2 - width  / 2,
                                y: y + h / 2 - height / 2,
                                url: "/redis/append_list_exist_key_value.html",
                                parameters: {
                                    title: "插入新值",
                                    view: tools.getView(),
                                    key: window.redis_key
                                }
                            })
                            if (modal === true) {
                                this.componentUpdate()
                            }
                        })

                    }}>新增
                    </div>
                    <div class="btn" onClick={() => {
                        setTimeout(() => {
                            let [x, y] = tools.windowPosition()
                            let [w, h] = tools.windowSize()
                            let scale = devicePixelRatio
                            let width = 320 * scale
                            let height = 240 * scale
                            let modal = tools.getView().modal({
                                width,
                                height,
                                x: x + w / 2 - width  / 2,
                                y: y + h / 2 - height / 2,
                                url: "/redis/clip_list.html",
                                parameters: {
                                    title: "裁剪list",
                                    view: tools.getView(),
                                    key: window.redis_key
                                }
                            })
                            if (modal === true) {
                                this.componentUpdate()
                            }
                        })

                    }}>裁剪
                    </div>
                    <div class="btn" onClick={() => {
                        tools.async_xcall("async_get_list_val",window.redis_key,0,Number(this.page.total))
                            .then(res => {
                                if (res.code !== 200) {
                                    return
                                }
                                this.exportFile(JSON.stringify(res.data.list) || "[]")
                            })
                    }}>导出
                    </div>
                </div>
            </div>
            <div class="table">
                <div class="tr">
                    <div class="th v v-index">index</div>
                    <div class="th k">内容</div>
                    <div class="th v v-a">操作</div>
                </div>
                <div class="list-tbody">
                    {
                        this.list.map((e, i) => {
                            let index = i + (this.page.current - 1) * this.page.size
                            return <div class="tr">

                                <div class="th v v-index">{index}</div>
                                <div class="th k">
                                    <div class="r-v">{e}</div>
                                    <div class="key-copy" onClick={() => this.doCopy(e)}>复制</div>
                                </div>
                                <div class="th v v-a">
                                    <div class="btn" onClick={() => {
                                        setTimeout(() => {
                                            let [x, y] = tools.windowPosition()
                                            let [w, h] = tools.windowSize()
                                            let scale = devicePixelRatio
                                            let width = 320 * scale
                                            let height = 200 * scale
                                            let modal = tools.getView().modal({
                                                width,
                                                height,
                                                x: x + w / 2 - width  / 2,
                                                y: y + h / 2 - height / 2,
                                                url: "/redis/edit_redis_list_value.html",
                                                parameters: {
                                                    title: "修改list的值",
                                                    view: tools.getView(),
                                                    index,
                                                    key: window.redis_key,
                                                    value: e
                                                }
                                            })
                                            if (modal === true) {
                                                this.componentUpdate()
                                            }
                                        })
                                    }}>修改
                                    </div>
                                    <div class="btn" onClick={() => {
                                        tools.confirm("确定要删除吗？")
                                            .then(res => {
                                                if (res === true) {
                                                    if (tools.xcall("delete_list_index_val", window.redis_key, e) === true) {
                                                        return tools.alert("删除成功！")
                                                            .then(() => {
                                                                this.componentUpdate()
                                                            })
                                                    }
                                                    tools.alert("删除失败！")
                                                }
                                            })
                                    }}>删除
                                    </div>
                                </div>
                            </div>
                        })
                    }
                </div>
            </div>
            {this.renderPage(i => {
                this.page.current = i
                this.componentUpdate()
            })}
        </div>
    }

}